var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var logger = require('morgan');

var app = express();
app.use(express.json({limit: '50mb'}));
// mongoose
require('./mongoose/mongo.js');


app.use(logger('dev'));
app.use(express.json());
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');

// bodyParser
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(cookieParser());

// 默认bodyParser对提交的json数据的默认限制在1mb，这里改为limit: 50mb
app.use(express.json({limit: '50mb'}));
app.use(express.static(path.join(__dirname, 'public')));

// 解决跨域请求的问题
app.all('*', (req, res, next) => {
  res.header("Access-Control-Allow-Origin", "http://localhost:3030");
  res.header("Access-Control-Allow-Headers", "Content-Type,Content-Length, Authorization, Accept,X-Requested-With");
  res.header("Access-Control-Allow-Methods","PUT,POST,GET,DELETE,OPTIONS");
  res.header("X-Powered-By",' 3.2.1')
  if(req.method=="OPTIONS") res.sendStatus(200); /*让options请求快速返回*/
  else next();
});

// 路由页面
var loginRouter = require('./routes/login');
var registerRouter = require('./routes/register');
var articleRouter = require('./routes/article');
var commentRouter = require('./routes/comment');
app.use('/login', loginRouter);
app.use('/register', registerRouter);
app.use('/article', articleRouter);
app.use('/comment', commentRouter);

// catch 404 and forward to error handler
app.use((req, res, next) => {
  next(createError(404));
});

// error handler
app.use((err, req, res, next) => {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});

module.exports = app;
